import { makeAutoObservable, observable } from 'mobx';
import * as api from './api';

export default class CompanyRouteStore {
  _args = {
    search: {
    },
    pg: {
      page: 0,
      sort: ['crDate;desc'],
      size: 10,
    },
  };
  total = 0;
  prices = [];
  consolePrice = [];
  loading = false;
  price_loading = false;
  _allItems = []; // 所有region的字典项
  cities = []; // 顶级节点
  groups = []; // 所有分组
  startCity = []; // 开始城市
  endCity = []; // 结束城市
  startStation = []; // 开始站点
  endStation = []; // 结束站点
  _selected = '';
  _priceStatus = '0';
  company = [];
  typeArgs = {
    0: 2,
    1: 1,
  }

  constructor(rootStore) {
    this.rootStore = rootStore;
    makeAutoObservable(this, { rootStore: false });
  }

  * fetchGroups() {
    this.loading = true;
    try {
      let items = yield api.allItems();
      this._allItems = [...items];
      this.cities = [...items].filter((item) => (!item.parentId)).sort((a, b) => a.itemId.localeCompare(b.itemId));
      items = items.filter((item) => (item.extras?.group?.value));
      items = items.map((item) => ({ name: item.extras.group.value, city: item.fullId.split(':')[0] }));
      this.groups = _.uniqBy(items, 'name').sort(); // (a, b) => a.name.localeCompare(b.name));
      this._selected = this.groups[0];
      // const oldGroup = this.getGroup(this._selected?.name);
      // this._selected = oldGroup || this.groups[0];

      this.cities.forEach((city) => {
        city.children = this.groupsForCity(city.itemId);
      });
    } finally {
      this.loading = false;
    }
  }

  groupsForCity(cityId) {
    return this.groups.filter((v) => (v.city === cityId)); // .concat([{ name: t`未分组`, city: cityId, regions: [] }]);
  }

  regionsForCity(cityId) { // 获取城市下的所有区域供选择
    return this._allItems.filter((v) => (v.fullId.match(new RegExp(`^${cityId}:`)))).map((v) => toJS(v));
  }

  /**
   * 使用设置的请求参数和分页配置请求列表数据
   * 分页参数为空时保持当前分页配置
   * @param {object} pgInfo 分页参数
   */
  * query(pgInfo) {
    _.mergeWith(this._args.pg, pgInfo, (o, s) => (_.isArray(o) ? s : undefined)); // 数组直接赋值，不合并
    const { search, pg } = toJS(this._args);
    search.type = this.typeArgs[this._priceStatus];
    search.priceType = this._priceStatus === '2' ? 2 : 1;
    if (!pg.sort?.length) delete pg.sort;
    this.loading = true;
    try {
      this.total = yield api.count({ search });
      this.prices = yield api.search({ search, pg });
    } finally {
      this.loading = false;
    }
  }

  * get(id) {
    const res = yield api.get(id);
    return observable(res);
  }

  * update(price) {
    yield api.update(price);
    yield this.query();
  }

  * create(price) {
    yield api.create(price);
    yield this.query();
  }

  * remove(price) {
    yield api.remove(price.id);
    yield this.query();
  }

  * updateState(price) {
    const { id, state } = price;
    yield api.update({ id, state: !state });
    yield this.query();
  }

  * cbvCompanyPriceCopy(args) {
    yield api.cbvCompanyPriceCopy(args);
    yield this.query();
  }

  * getCompany(data) {
    const company = yield api.getCompany({ ...data });
    const selectData = company.map((item) => {
      return ({
        label: item.name,
        value: item.id,
      });
    });
    selectData.push({ label: '【平台线路】', value: '【平台线路】' });
    this.company = selectData;
  }

  * companyConsolePrice(data) {
    this.price_loading = true;
    try {
      const prices = yield api.companyConsolePrice(data);
      this.consolePrice = prices;
    } finally {
      this.price_loading = false;
    }
  }
  async exitingLines(price) {
    const {
      companyId,
      priceType,
      startMainArea,
      endMainArea,
      startMinorAreas,
      endMinorAreas,
      portTypes: ports,
    } = toJS(price);
    return api.existingLines({
      companyId,
      priceType,
      startMainArea,
      endMainArea,
      startMinorAreas,
      endMinorAreas,
      ports,
      excludeId: price.id,
    });
  }

  * getStartCity(args) {
    const start = yield api.getScCity(args);
    this.startCity = start.map((item) => ({
      label: item.name,
      value: item.itemId,
    }));
  }

  * getEndCity(args) {
    const start = yield api.getScCity(args);
    this.endCity = start.map((item) => ({
      label: item.name,
      value: item.itemId,
    }));
  }

  * getStartStation(data) {
    const start = yield api.getScStation(data);
    const temp = start.reduce((acc, arr) => {
      return acc.concat(arr.children);
    }, []);
    this.startStation = temp.map((item) => ({
      label: item.name,
      value: item.id,
    }));
  }

  * getEndStation(data) {
    const end = yield api.getScStation(data);
    const temp = end.reduce((acc, arr) => {
      return acc.concat(arr.children);
    }, []);
    this.endStation = temp.map((item) => ({
      label: item.name,
      value: item.id,
    }));
  }

  idx(i) {
    return this._args.pg.page * this._args.pg.size + i + 1;
  }

  get pg() {
    return this._args.pg;
  }

  set pg(pg) {
    this.query({ ...pg });
  }

  get priceStatus() {
    return this._priceStatus;
  }

  set priceStatus(value) {
    this._priceStatus = value;
    this._args.pg.page = 0;
    this.query({ page: 0 });
  }

  get search() {
    this._args.pg.page = 0;
    return this._args.search;
  }

  set search(search) {
    this._args.pg.page = 0;
    this._args.search = search;
    this.query({ page: 0 });
  }

  get tableSort() {
    if (this._args.pg.sort?.length) {
      const [fn, dir] = this._args.pg.sort[0].split(';');
      return { [fn]: dir };
    }
    return undefined;
  }
}
